<?php

namespace app\api\services;

use Qcloud\Sms\SmsSingleSender;

class QCloudSmsService
{

    // 短信应用SDK AppID
    protected $appid = 1400944402; // 1400开头

    // 短信应用SDK AppKey
    protected $appKey = '09fa19164f1cde05809632892a27424b';

    // 短信模板ID，需要在短信应用中申请
    protected $templateId = 1043067;

    // 签名
    protected $smsSign = '兰考县行政审批和政务信息';    // NOTE: 这里的签名只是示例，请使用真实的已申请的签名，签名参数使用的是`签名内容`，而不是`签名ID`

    protected static $instance = null;

    private function __construct()
    {
    }

    private function __clone()
    {
    }

    public static function getInstance()
    {
        if (self::$instance === null) {
            self::$instance = new static();
        }
        return self::$instance;
    }

    /**
     * @param $phone
     * @param $content
     * @return mixed
     * @throws \Exception
     */
    public function sendSms($phone, $content)
    {
        // 指定模板ID单发短信
        try {
            $sender  = new SmsSingleSender($this->appid, $this->appKey);
            $params  = [$content];
            $templId = $this->templateId;
            $result  = $sender->sendWithParam("86", $phone, $params, $templId, $this->smsSign, "", "");  // 签名参数未提供或者为空时，会使用默认签名发送短信
            return json_decode($result, true);
        }
        catch (\Exception $e) {
            throw $e;
        }
    }
}
